from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from config import settings
from database import test_db_connection, test_redis_connection

# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="邮件统一发送平台API",
    debug=settings.debug
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],  # 前端地址
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    print(f"🚀 启动 {settings.app_name} v{settings.app_version}")
    
    # 测试数据库连接
    test_db_connection()
    
    # 测试Redis连接
    test_redis_connection()
    
    print("✅ 应用启动完成")


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理"""
    print("👋 应用正在关闭...")


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用{settings.app_name}",
        "version": settings.app_version,
        "status": "running"
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "app_name": settings.app_name,
        "version": settings.app_version
    }


# 添加静态文件服务
app.mount("/uploads", StaticFiles(directory=settings.upload_dir), name="uploads")

# 添加路由
from routers import auth, data_sources, contacts, email_configs, email_templates, data_source_fields, email_send, file_upload
app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
app.include_router(data_sources.router, prefix="/api/data-sources", tags=["数据源"])
app.include_router(contacts.router, prefix="/api/contacts", tags=["联系人"])
app.include_router(email_configs.router, prefix="/api/email-configs", tags=["邮件配置"])
app.include_router(email_templates.router, prefix="/api/templates", tags=["邮件模板"])
app.include_router(data_source_fields.router, tags=["数据源字段"])
app.include_router(email_send.router, tags=["邮件发送"])
app.include_router(file_upload.router, prefix="/api/files", tags=["文件上传"])

# 其他路由将来添加
# from routers import users, emails
# app.include_router(users.router, prefix="/api/users", tags=["用户"])
# app.include_router(emails.router, prefix="/api/email", tags=["邮件发送"])


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.debug
    )
